package ui.fragment;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.youth.banner.Banner;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import adapter.MallGoodsAdapter;
import adapter.MallGradeAdapter;
import adapter.MallSubjectAdapter;
import base.BaseBean;
import base.fragment.BaseNetFragment;
import bean.GoodsBean;
import bean.GoodsGrade;
import bean.GoodsSchedule;
import bean.UnreadMsgBean;
import student.andlei.com.student.R;
import ui.activity.MainActivity;
import ui.activity.MessageActivity;
import ui.activity.WebActivity;
import ui.activity.mall.MallCourseActivity;
import utils.GsonUtils;
import utils.ImageLoaderUtils;

/**
 * 商城页
 */
public class MallFragment extends BaseNetFragment {

    public static final String SHOP_INDEX = "/Shop/index";
    public static final String SHOP_GETSCHEDULES = "/Shop/getSchedules";
    public static final String SHOP_GRADE_SUBJECTS = "/Shop/gradeSubjects";


    private Banner mBanner;
    private TextView mTvFamousTitle;
    private RecyclerView mRvFamous;
    private RecyclerView mRvGrade;
    private RecyclerView mRvSubject;
    private RecyclerView mRvSchedule;
    private EditText mEtSearch;
    private LinearLayout mLlEmptyFootView;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private MallGoodsAdapter mFamousAdapter;
    private List<GoodsBean.Schedule> mFamousLists = new ArrayList<>();
    private List<GoodsGrade> mDegressLists = new ArrayList<>();
    private List<GoodsGrade.GradeBean> mDegressSubjectLists = new ArrayList<>();
    private List<GoodsBean.Schedule> mScheduleLists = new ArrayList<>();
    private MallGradeAdapter mGradeAdapter;
    private MallSubjectAdapter mSubjectAdapter;
    private MallGoodsAdapter mScheduleAdapter;
    private TextView tv_msg_number;
    private ImageView img_msg;
    private int mCurPage;
    private int mMaxPage;

    public static Fragment getInstance() {
        return new MallFragment();
    }
    @Override
    public void success(String action, BaseBean baseBean) {
        if (TextUtils.equals(action, SHOP_INDEX)) {
            mSwipeRefreshLayout.setRefreshing(false);
            GoodsBean goodsBean = (GoodsBean) GsonUtils.JSONToObject(GsonUtils.beanToJSONString(baseBean.data), GoodsBean.class);
            if (goodsBean.ads != null && goodsBean.ads.size() != 0) {
                mBanner.setVisibility(View.VISIBLE);
                mBanner.setImages(goodsBean.ads);
                mBanner.start();
            } else {
                mBanner.setVisibility(View.GONE);
            }
            if (goodsBean.famous == null || goodsBean.famous.size() == 0) {
                mTvFamousTitle.setVisibility(View.GONE);
                mRvFamous.setVisibility(View.GONE);
            } else {
                mTvFamousTitle.setVisibility(View.VISIBLE);
                mRvFamous.setVisibility(View.VISIBLE);
                mFamousLists.clear();
                mFamousLists.addAll(goodsBean.famous);
                mFamousAdapter.setNewData(mFamousLists);
            }
            post(SHOP_GRADE_SUBJECTS,BaseBean.class,false);
        } else if (TextUtils.equals(action, SHOP_GETSCHEDULES)) {
            GoodsSchedule goodsSchedule = (GoodsSchedule) GsonUtils.JSONToObject(GsonUtils.beanToJSONString(baseBean.data), GoodsSchedule.class);
            mCurPage = goodsSchedule.page.cpage;
            mMaxPage = goodsSchedule.page.total_page;
            if (mCurPage == 1) {
                mScheduleLists.clear();
                if (goodsSchedule.list.isEmpty()) {
                    mLlEmptyFootView.setVisibility(View.VISIBLE);
                } else {
                    mLlEmptyFootView.setVisibility(View.GONE);
                }
            }
            mScheduleLists.addAll(goodsSchedule.list);
            mScheduleAdapter.setNewData(mScheduleLists);
        } else if (TextUtils.equals(action, SHOP_GRADE_SUBJECTS)) {
            List<GoodsGrade> goodsGrades =GsonUtils.getInstance(getActivity()).parseNoHeaderJArray(baseBean, GoodsGrade.class);
            //年级
            mDegressLists.clear();
            mDegressLists.addAll(goodsGrades);
            mGradeAdapter.setNewData(mDegressLists);
            //科目
            mSubjectAdapter.setNewData(mGradeAdapter.getCheckDegress().list);
            loadSchedules(true, mSubjectAdapter.getCheckSubject().subject_id, mGradeAdapter.getCheckDegress().grade_id, "");
        }else if(action.equals("personal/getUnreadMsg")){
            UnreadMsgBean bean = (UnreadMsgBean) GsonUtils.getInstance(context).parseComplexJArrayByCommon(baseBean, UnreadMsgBean.class);
            if (bean.count <= 0) {
                tv_msg_number.setVisibility(View.GONE);
            } else {
                tv_msg_number.setText(bean.count + "");
            }
        }else if(action.equals("Qa/getNewsNumber")){
            UnreadMsgBean bean = (UnreadMsgBean) GsonUtils.getInstance(context).parseComplexJArrayByCommon(baseBean,UnreadMsgBean.class);
            if(bean.count>0){
                MainActivity.img_red_point.setText(bean.count+"");
                MainActivity.img_red_point.setVisibility(View.VISIBLE);
            }else {
                MainActivity.img_red_point.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void error(String action, Throwable e) {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_mall;
    }

    @Override
    protected void findViews() {
        img_msg = getView(R.id.img_msg);
        tv_msg_number = getView(R.id.tv_msg_number);
        mSwipeRefreshLayout = getView(R.id.swipeRefreshLayout);
        mRvSchedule = getView(R.id.rv_schedule);
        GridLayoutManager scheduleLayoutManage = new GridLayoutManager(getContext(), 4);
        mRvSchedule.setLayoutManager(scheduleLayoutManage);
        mScheduleAdapter = new MallGoodsAdapter(R.layout.item_mall_goods, mScheduleLists);
        mRvSchedule.setAdapter(mScheduleAdapter);

        mLlEmptyFootView = (LinearLayout) LayoutInflater.from(getActivity()).inflate(R.layout.empty_course, null);
        mScheduleAdapter.addFooterView(mLlEmptyFootView);

        View headerView = LayoutInflater.from(getActivity()).inflate(R.layout.mall_index_header, mRvSchedule, false);
        mTvFamousTitle = getView(headerView, R.id.tv_famous_title);
        mRvFamous = getView(headerView, R.id.rv_famous);
        mRvGrade = getView(headerView, R.id.rv_grade);
        mRvSubject = getView(headerView, R.id.rv_subject);
        mEtSearch = getView(headerView, R.id.edittext_search);
        mBanner = getView(headerView, R.id.banner);
        mBanner.setImageLoader(mImageLoader);
        mBanner.setDelayTime(3000);
        //添加头部
        mScheduleAdapter.addHeaderView(headerView);

        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                post(SHOP_INDEX, BaseBean.class, false);
            }
        });
    }

    @Override
    protected void formatViews() {
        img_msg.setOnClickListener(this);
        //名师讲堂.
        GridLayoutManager famousLayoutManage = new GridLayoutManager(getContext(), 4);
        mRvFamous.setLayoutManager(famousLayoutManage);
        mFamousAdapter = new MallGoodsAdapter(R.layout.item_mall_goods, mFamousLists);
        mRvFamous.setAdapter(mFamousAdapter);
        mFamousAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                GoodsBean.Schedule schedule = mFamousAdapter.getItem(position);
                MallCourseActivity.startMallCourseActivity(getActivity(), schedule.schedule_id);
            }
        });
        //年级
        LinearLayoutManager gradelinearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
        mRvGrade.setLayoutManager(gradelinearLayoutManager);
        mGradeAdapter = new MallGradeAdapter(R.layout.item_mall_grade, mDegressLists);
        mRvGrade.setAdapter(mGradeAdapter);
        mGradeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                mGradeAdapter.setCheckDegress((GoodsGrade) adapter.getItem(position));
                mGradeAdapter.notifyDataSetChanged();
                //科目
                mSubjectAdapter.setNewData(mGradeAdapter.getCheckDegress().list);
                mSubjectAdapter.setCheckSubject(null);

                loadSchedules(true, mSubjectAdapter.getCheckSubject().subject_id, mGradeAdapter.getCheckDegress().grade_id, "");
            }
        });
        //科目
        LinearLayoutManager subjectLinearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
        mRvSubject.setLayoutManager(subjectLinearLayoutManager);
        mSubjectAdapter = new MallSubjectAdapter(R.layout.item_mall_subject, mDegressSubjectLists);
        mRvSubject.setAdapter(mSubjectAdapter);
        mSubjectAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                mSubjectAdapter.setCheckSubject((GoodsGrade.GradeBean) adapter.getItem(position));
                mSubjectAdapter.notifyDataSetChanged();
                loadSchedules(true, mSubjectAdapter.getCheckSubject().subject_id, mGradeAdapter.getCheckDegress().grade_id, "");
            }
        });
        //搜索
        mEtSearch.setOnEditorActionListener(mOnEditorActionListener);
        //
        mScheduleAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                GoodsBean.Schedule schedule = mScheduleAdapter.getItem(position);
                MallCourseActivity.startMallCourseActivity(getActivity(), schedule.schedule_id);
            }
        });
        //滚动监听
        mRvSchedule.addOnScrollListener(mOnScrollListener);
    }

    @Override
    protected void formatData() {
        post(SHOP_INDEX, BaseBean.class, true);
    }

    @Override
    protected void getBundle() {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.img_msg:
                jumpTo(MessageActivity.class);
                break;
        }
    }

    protected void loadSchedules(boolean isRefresh, String subject_id, String degree_id, String title) {
        if (isRefresh) {
            mCurPage = 1;
        } else {
            mCurPage = mCurPage + 1;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("subject_id", subject_id);
        map.put("degree_id", degree_id);
        if (!TextUtils.isEmpty(title)) {
            map.put("title", title);
        }
        post(SHOP_GETSCHEDULES, map, BaseBean.class, false);
    }

    ImageLoader mImageLoader = new ImageLoader() {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            final GoodsBean.Ads ads = (GoodsBean.Ads) path;
            ImageLoaderUtils.loadImage(context, ads.image, imageView);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (!TextUtils.isEmpty(ads.link)) {
                        MallCourseActivity.startMallCourseActivity(getActivity(), ads.link);
                    }
//                    else if (!TextUtils.isEmpty(ads.link)) {
//                        WebActivity.startWebActivity(getActivity(), ads.link);
//                    }
                }
            });
        }
    };

    /**
     * 搜索
     */
    TextView.OnEditorActionListener mOnEditorActionListener = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
            String content = mEtSearch.getText().toString();
            loadSchedules(true, mSubjectAdapter.getCheckSubject().subject_id, mGradeAdapter.getCheckDegress().grade_id, content);
            return false;
        }
    };

    RecyclerView.OnScrollListener mOnScrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
            //当前RecyclerView显示出来的最后一个的item的position
            int lastPosition = -1;
            //当前状态为停止滑动状态SCROLL_STATE_IDLE时
            if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                if (layoutManager instanceof GridLayoutManager) {
                    //通过LayoutManager找到当前显示的最后的item的position
                    lastPosition = ((GridLayoutManager) layoutManager).findLastVisibleItemPosition();
                } else if (layoutManager instanceof LinearLayoutManager) {
                    lastPosition = ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition();
                } else if (layoutManager instanceof StaggeredGridLayoutManager) {
                    //因为StaggeredGridLayoutManager的特殊性可能导致最后显示的item存在多个，所以这里取到的是一个数组
                    //得到这个数组后再取到数组中position值最大的那个就是最后显示的position值了
                    int[] lastPositions = new int[((StaggeredGridLayoutManager) layoutManager).getSpanCount()];
                    ((StaggeredGridLayoutManager) layoutManager).findLastVisibleItemPositions(lastPositions);
                    lastPosition = findMax(lastPositions);
                }
                //时判断界面显示的最后item的position是否等于itemCount总数-1也就是最后一个item的position
                //如果相等则说明已经滑动到最后了
                if (lastPosition == recyclerView.getLayoutManager().getItemCount() - 1) {
                    if (mCurPage < mMaxPage) {
                        loadSchedules(false, mSubjectAdapter.getCheckSubject().subject_id, mGradeAdapter.getCheckDegress().grade_id, "");
                    }
                }
            }
        }

        @Override
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
        }
    };

    //找到数组中的最大值
    private int findMax(int[] lastPositions) {
        int max = lastPositions[0];
        for (int value : lastPositions) {
            if (value > max) {
                max = value;
            }
        }
        return max;
    }
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden){
            post("Qa/getNewsNumber",BaseBean.class,false);
            post("personal/getUnreadMsg",BaseBean.class,false);
        }
    }
}
